package com.lindenvalley.ch.ice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;

public class IceApplicationActivity extends Activity {
    /** Called when the activity is first created. */
	
	private Uri uriData;
	private BitmapDrawable backgroundDrawable;
	private MediaPlayer mediaPlayer;
	private PreviewView view;
	private Animation animation;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        uriData = getIntent().getData();        
        
        setContentView(R.layout.ice_photo);        
        
		view = (PreviewView) findViewById(R.id.imageViewPhoto);
		animation = AnimationUtils.loadAnimation(this, R.anim.alpha);
		animation.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				mediaPlayer = MediaPlayer.create(IceApplicationActivity.this, R.raw.oledenenie_zamorozka);
				mediaPlayer.start();
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				
			}
		});
		view.setAnimation(animation);        
        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    protected void onDestroy(){    	
    	if (mediaPlayer != null && mediaPlayer.isPlaying()){
    		try{
    			mediaPlayer.stop();
    		} catch (IllegalStateException ex){
    			ex.printStackTrace();
    		}
    		
    	}
    	super.onDestroy();
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	
    	int itemId = item.getItemId();
    	Intent intent;
		switch (itemId) {
		case R.id.itemShare:						
			File file = saveFile();
			if (file != null && file.exists()){
				MediaScannerConnection.scanFile(this,
	                    new String[] { file.toString() }, null,
	                    new MediaScannerConnection.OnScanCompletedListener() {
	                public void onScanCompleted(String path, Uri uri) {
	                    Log.i("ExternalStorage", "Scanned " + path + ":");
	                    Log.i("ExternalStorage", "-> uri=" + uri);
	                    Intent intent = new Intent("android.intent.action.SEND");
	    				intent.addCategory("android.intent.category.DEFAULT");
	    				intent.putExtra(Intent.EXTRA_STREAM, uri);			
	    				
	    				intent.setType("image/jpeg");
	    				startActivity(intent);
	                }
	            });
			}
			
			break;
		case R.id.itemOpen:
			saveFile();			
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");			
			startActivityForResult(intent, 0);			
			break;
		
		case R.id.itemPhoto:
			saveFile();
			intent = new Intent("android.media.action.IMAGE_CAPTURE");
			startActivityForResult(intent, 0);
			break;

		}
		return true;
    }
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		InputStream is;
        Options opt = new Options();
		try {
			is = getContentResolver().openInputStream(uriData);			
			opt.inJustDecodeBounds = true;			
			BitmapFactory.decodeStream(is, null, opt);
			is.close();
			if (opt.outWidth > opt.outHeight){
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			} else {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
			
			is = getContentResolver().openInputStream(uriData);
			DisplayMetrics dm = new DisplayMetrics();			
			
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			int w = dm.widthPixels;			
			int h = dm.heightPixels;			
			opt.inSampleSize = Math.max(opt.outWidth/w, opt.outHeight/h);
			opt.inJustDecodeBounds = false;
			is = getContentResolver().openInputStream(uriData);
			Bitmap bitmap = BitmapFactory.decodeStream(is, null, opt);
			bitmap  = Bitmap.createScaledBitmap(bitmap, w, h, true);
			backgroundDrawable = new BitmapDrawable(bitmap);
			
			LinearLayout mainLayout = (LinearLayout) findViewById(R.id.MainBackground);
			mainLayout.setBackgroundDrawable(backgroundDrawable);
			
			is.close();
			view.initBitmap();
			animation.reset();
			view.startAnimation(animation);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
//		  Intent intent = new Intent(this, IceApplicationActivity.class);
		  uriData = data.getData();
//		  if (dataUri != null){			  
//			  intent.setData(dataUri);
//			  startActivity(intent);
//			  
//		  }
	  }
	}
    
    private File saveFile(){
    	PreviewView view = (PreviewView) findViewById(R.id.imageViewPhoto);
		
		Matrix matrix = new Matrix();
		Bitmap b = backgroundDrawable.getBitmap();
		Canvas canvas = new Canvas(b);
		canvas.drawBitmap(view.getBitmap(), matrix, null);
		ContentResolver resolver = getContentResolver();
		Cursor cursor = resolver.query(uriData, null, null, null, null);
		int index = cursor.getColumnIndex(Images.Media.DISPLAY_NAME);
		cursor.moveToFirst();
		String fileName = cursor.getString(index);
		String[] fileAndExtention = fileName.split("\\.");
		if (fileAndExtention != null && fileAndExtention.length >= 2)
			fileName = fileAndExtention[0];

//		String url = Images.Media.insertImage(resolver, b, "someImage", "This is my first image file");			
//		Uri uri = Uri.parse(url);			

		File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		if (!path.exists())
			path.mkdir();
		
		File file = new File(path, fileName.concat("_frost.jpg"));
		try {
			OutputStream os = new FileOutputStream(file);
			b.compress(Bitmap.CompressFormat.JPEG, 50, os);
			os.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		return file;
    	
    }
}